<script setup lang="ts">
/**
 * 系统管理-系统设置-子菜单列表
 */
import {onMounted, ref} from 'vue'
import {getMenuListApi} from '@/assets/api/systemManagement/system/menu'
import {Delete, Plus} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {iconList} from '@/components/icons/iconList.js'
import YwzIcon from '@/components/icons/YWZIcon.vue'
import UploadImage from '@/components/base/UploadImage.vue'
import {downloadFileUrl} from "@/assets/api/systemManagement/data/file";
import {getMenuSubListByRemarkApi, saveMenuSubApi} from "@/assets/api/systemManagement/system/menuSub";

// 记录id节点最大值
const countId = ref(0)
// 获取菜单列表
const menuList = ref()
const getList = () => {
  getMenuListApi().then(res => {
    if (res.data.code == 200) {
      menuList.value = []
      menuList.value.push({name: "全部", remark: "all"})
      menuList.value.push(...res.data.data.list)
    } else
      ElMessage.error({message: res.data.data, type: 'error'})
  })
}

// 选择菜单
const selectedMenu = ref()
const props = {
  label: 'name',
  value: 'remark',
}
const selectedMenuHandleChange = (val: any) => {
  getMenuSubList()
}

// 菜单子表
const menuSubList = ref()
const getMenuSubList = () => {
  getMenuSubListByRemarkApi(selectedMenu.value[selectedMenu.value.length - 1]).then(res => {
    if (res.data.code == 200) {
      if (res.data.data.list.length == 0) {
        menuSubList.value = [{
          id: 0,
          name: '暂无数据',
          children: [],
          parentId: selectedMenu.value[selectedMenu.value.length - 1]
        }]
        countId.value = res.data.data.topId + 1
        return
      }
      menuSubList.value = res.data.data.list
      countId.value = res.data.data.topId + 1
    } else
      ElMessage.error({message: res.data.data, showClose: true})
  })
}

// 节点映射
const menuProps = {
  label: 'name',
  children: 'children'
}

// 保存菜单更改
const saveMaster = () => {
  menuList.value.forEach((item: any) => {
    item.isParent = 1
  })
  const obj = {
    key: 'master',
    list: menuSubList.value
  }
  const menuSubListJson = JSON.stringify(obj, null, 2)
  saveMenuSubApi(menuSubListJson).then(res => {
    if (res.data.code === 200)
      ElMessage.success({message: res.data.data, showClose: true})
    else
      ElMessage.error({message: res.data.data, showClose: true})
  })
}

// 添加节点
const append = (data: any) => {
  // 菜单名称确认框
  ElMessageBox.prompt('请输入菜单名称', 'Tip', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    inputPattern:
      /([\u4e00-\u9fa5]|\w)+/,
    inputErrorMessage: '菜单名称'
  }).then(({value}) => {
    // 添加节点
    const newChild = {
      id: countId.value++,
      name: value,
      children: [],
      parentId: selectedMenu.value[selectedMenu.value.length - 1]
    }
    if (!data.children) {
      data.children = []
    }
    data.children.push(newChild)
    menuSubList.value = [...menuSubList.value]
    ElMessage({
      type: 'success',
      message: `添加成功`
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '请输入中文字母数字'
    })
  })
}

// 删除节点
const remove = (node: any, data: any) => {
  const parent = node.parent
  const children = parent.data.children || parent.data
  const index = children.findIndex((d: any) => d.id === data.id)
  children.splice(index, 1)
  menuSubList.value = [...menuSubList.value]
}

// 菜单图标变更
const iconChange = (data: any, val: string) => {
  data.icon = val
}

// 上传图片弹窗
const dialogVisible = ref(false)
const updateMenu = ref()
const updateImage = (data: any) => {
  console.log(data)
  updateMenu.value = data
  dialogVisible.value = true
}

// 上传图片回调
const uploadImageCallBack = (imageName: any) => {
  updateMenu.value.imgUrl = imageName
}

onMounted(() => {
  getList()
})

// 菜单图标列表
const options = iconList
</script>

<template>
  <div class="app-container">
    <!-- 警告条 -->
    <el-row style="padding:0.4%">
      <el-col :span="24">
        <el-alert title="菜单子表只能扩展到二级，二级以上的子菜单将无法保存" type="warning" show-icon/>
      </el-col>
    </el-row>
    <!-- 菜单树头 -->
    <el-row style="padding:0.4%">
      <el-col :span="24">
        <h4>选择菜单：
          <el-cascader :props="props" v-model="selectedMenu" :options="menuList" @change="selectedMenuHandleChange"/>
          <el-button style="margin-left: 20px" type="primary" @click="saveMaster">保存更改</el-button>
        </h4>
      </el-col>
    </el-row>
    <!-- 菜单树 -->
    <el-row style="padding:0.4%">
      <el-col :span="24">
        <el-tree
          class="tree-content"
          :data="menuSubList"
          :draggable="true"
          default-expand-all
          node-key="id"
          :props="menuProps"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span><el-input size="small" style="width: 80px;" v-model="data.name"
                              placeholder="请输入菜单名"></el-input></span>
              <span>
                <a style="margin-left: 8px" @click="append(data)">
                  <el-icon><Plus/></el-icon>
                </a>
                <a style="margin-left: 8px" @click="remove(node, data)"> <el-icon><Delete/></el-icon> </a>
              </span>
              <span style="margin-left: 16px">
                图标：
                  <el-select
                    placeholder="选择图标"
                    size="small"
                    style="width: 90px"
                    @change="iconChange(data, $event)"
                    v-model="data.icon"
                    clearable
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                      <ywz-icon :icon="item.value" style="width: 20px;height: 20px"></ywz-icon>
                      {{ item.label }}
                    </el-option>
                  </el-select>
              </span>
              <span class="menu-span">
                别名：
                  <el-input size="small" style="width: 80px;" v-model="data.alias"
                            placeholder="请输入别名"></el-input>
              </span>
              <span class="menu-span">
                图片：
                  <img :src="downloadFileUrl+data.imgUrl+'&contentType=image/png'" @click="updateImage(data)" width="20"
                       height="20" alt="暂无">
              </span>
              <span class="menu-span">
                前台可见：
                 <el-switch
                   v-model="data.visible"
                   style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                   :active-value="1"
                   :inactive-value="0"
                 />
              </span>
              <span class="menu-span">
                菜单地址
                  <el-input size="small" style="width: 300px;" v-model="data.menuUrl"
                            placeholder="请输入菜单地址"></el-input>
              </span>
              <span class="menu-span">
                关联标识
                  <el-input size="small" style="width: 300px;" v-model="data.remark"
                            placeholder="需要与子表的关联标识对应"></el-input>
              </span>
            </span>
          </template>
        </el-tree>
      </el-col>
    </el-row>
    <!--  新增、编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="上传图片"
      width="300"
      :destroy-on-close="true"
    >
      <upload-image :image-name="updateMenu.imgUrl" @success="uploadImageCallBack"></upload-image>
    </el-dialog>
  </div>
</template>

<style scoped>
.app-container {
  width: 100%;
  height: 100%;
}

.tree-content {
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.menu-span {
  border-left: #aeaeae 3px solid;
  margin-left: 20px;
  margin-right: 20px;
  background-color: #fdfdfd;
}

</style>
